package com.med.meddataintegrator.jwt.service.Impl;

import com.med.meddataintegrator.common.enums.UserRole;
import com.med.meddataintegrator.common.pojo.dos.UserDo;
import com.med.meddataintegrator.common.mapper.UserDoMapper;
import com.med.meddataintegrator.jwt.pojo.LoginUserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserDoMapper userDoMapper;


    /**
     *  实现查询用户角色和权限
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserDo userDo = userDoMapper.selectByUserName(username);
        List<String> permissions = new ArrayList<>();

        if (Objects.isNull(userDo)) {
            log.warn("用户不存在");
            throw new UsernameNotFoundException("用户不存在");
        }
        if (userDo != null) {
            //TODO 实现用户角色表 以及 用户表的关联   需要创建角色表  以及权限表?   还是两个表合一?
            // 获取用户角色
            Integer role = userDo.getRole();
            if (role == UserRole.ADMIN.getRole()){
                permissions.add(UserRole.ADMIN.getRoleName());
            }
            if (role == UserRole.DOCTOR.getRole()){
                permissions.add(UserRole.DOCTOR.getRoleName());
            }
            if (role == UserRole.PATIENT.getRole()){
                permissions.add(UserRole.PATIENT.getRoleName());
            }


        }

        // TODO 此处权限为null
        log.info("登录的用户角色 {}",userDo);
        return new LoginUserInfoVo(userDo,permissions);
    }

    // 用来实现查询用户角色和权限

}
